package com.joelaws.prototype.server.blackberry;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.server.dao.DAOFactory;

public class UserLogin extends Resource {

	private String email;

	private String password;

	public UserLogin(Context context, Request request, Response response) {
		super(context, request, response);
		String[] data = request.getResourceRef().getRemainingPart().split("&");

		if (data != null && data.length == 2) {
			String[] user;

			user = data[0].split("=");
			if (user != null && user.length == 2) {
				email = user[1];
			}

			user = data[1].split("=");
			if (user != null && user.length == 2) {
				password = user[1];
			}
		}
		super.getVariants().add(new Variant(MediaType.TEXT_PLAIN));
	}

	@Override
	public Representation getRepresentation(Variant variant) {
		if (email == null || password == null) {
			return new StringRepresentation("Invalid userID or action",
					MediaType.TEXT_PLAIN);
		}

		String userID = "-1";
		try {
			User user = DAOFactory.getUserDAO().getUser(email, password);
			if (user != null) {
				userID = "" + user.getUserID();
			}
		} catch (Exception e1) {
			userID = "Error loging meeting";
		}
		Representation representation = new StringRepresentation(userID,
				MediaType.TEXT_PLAIN);
		return representation;
	}

	public static String getURL() {
		return "/login";
	}
}
